/**
 * 
 */
package com.slink.fxfk.common.action;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.io.FileUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.slink.fxfk.common.domain.bo.BUser;
import com.slink.fxfk.common.domain.po.PAvatartmp;
import com.slink.fxfk.framework.exception.FXFKException;
import com.slink.fxfk.framework.util.CustomModelAndView;
import com.slink.fxfk.framework.util.ImageUtil;
import com.slink.fxfk.framework.util.ServletHelper;
import com.slink.fxfk.framework.util.SessionUtil;
import com.slink.fxfk.framework.util.StringUtil;

/**
 * @author 新
 *
 */
public class RegisterAction {

	@RequestMapping(method = RequestMethod.POST)
	public CustomModelAndView addRegisterUser(@Valid BUser user,
			BindingResult bindingResult,
			@RequestParam(value = "image", required = false) MultipartFile image) {

		if (bindingResult.hasErrors()) {
			return new CustomModelAndView("/auth/register");
		}

		// 处理保存user到数据库逻辑
		// ............

		if (!image.isEmpty()) {
			validateImage(image);

			try {
				saveImage(image.getOriginalFilename(), image);
			} catch (Exception e) {
				bindingResult.reject(e.getMessage());
				return new CustomModelAndView("/auth/register");
			}
		}

		return new CustomModelAndView("redirect:/success");
	}

	private void validateImage(MultipartFile file) {
		if (!file.getContentType().equals("image/jpeg")) {
			throw new FXFKException("直接收 JPG 格式图片");
		}
	}

	private void saveImage(String filename, MultipartFile image)
			throws Exception {

		try {
			File file = new File(ServletHelper.getServletContext()
					.getContextPath() + "/resourcefiles/" + filename);
			FileUtils.writeByteArrayToFile(file, image.getBytes());
		} catch (IOException e) {
			throw new FXFKException("上传图片失败");
		}
	}

	/**
	 * 上传头像原文件
	 * 
	 * @param request
	 * @param memberIcon
	 * @return
	 * @throws IOException
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/avatar/orig_img", produces = { "text/html" })
	public CustomModelAndView uploadMemberImg(HttpServletRequest request)
			throws IOException {
		CustomModelAndView imv = new CustomModelAndView();

		MultipartFile avatarFile = null;
		MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = mulRequest.getFileMap();
		for (Entry<String, MultipartFile> entry : fileMap.entrySet()) {
			avatarFile = entry.getValue();
		}

		if (avatarFile == null
				|| !ImageUtil.isImgFile(avatarFile.getInputStream())) {
			throw new FXFKException("0101010");
		}

		// 创建图片临时文件
		String realpath = request.getSession().getServletContext()
				.getRealPath("/");
		String filePath = realpath + "/avatar/" + System.currentTimeMillis();
		File f = new File(filePath);
		PAvatartmp avatartmp = null;
		try {
			FileUtils.copyInputStreamToFile(avatarFile.getInputStream(), f);
			ImageUtil.resize(filePath, 300, 400, false);
			// 将图片以字节数组的方式保存到数据库中
			// avatartmp =
			// this.resService.createAvatartmp(FileUtils.readFileToByteArray(f));
			imv.addObject("avatarId", avatartmp.getId());
		} catch (Exception e) {
			// 删除数据库中的临时文件
			if (avatartmp != null)
				// this.resService.delAvatartmp(avatartmp.getId());
				e.printStackTrace();
		} finally {
			// 删除临时文件
			FileUtils.deleteQuietly(f);
		}

		return imv;
	}

	/**
	 * 创建会员头像,保存用户裁剪后的头像
	 * 
	 * @param request
	 * @param imgPath
	 * @param x
	 * @param y
	 * @param w
	 * @param h
	 * @return
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/avatar/add", method = RequestMethod.POST)
	public CustomModelAndView saveMemberIcon(HttpServletRequest request,
			String avatarId, Integer x, Integer y, Integer w, Integer h) {
		CustomModelAndView imv = new CustomModelAndView();
		if (StringUtil.isBlank(avatarId)) {
			throw new FXFKException("0101010");
		}
		BUser member = (BUser) SessionUtil.getMemberSession(request);
		if (member == null) {
			return new CustomModelAndView("redirect:/common/login.html");
		}

		String realpath = request.getSession().getServletContext()
				.getRealPath("/");
		String filePath = realpath + "/avatar/" + System.currentTimeMillis();
		File file = new File(filePath);
		// 查询原图临时文件
		// 从数据库中获取临时图片
		PAvatartmp avatartmp = null;
		// PAvatartmp avatartmp = this.resService.getAvatartmp(avatarId);
		try {
			// 裁剪图片
			FileUtils.writeByteArrayToFile(file, avatartmp.getContent());
			ImageUtil.cut(file, x, y, w, h);
			// 缩放图片
			ImageUtil.resize(filePath, 100, 100, false);
			// 保存用户头像
			// BAvatar bAvatar = this.resService.createAvatar(member.getId(),
			// null, FileUtils.readFileToByteArray(file));
			// imv.addObject("avatarId", bAvatar.getId());
			// 更新会员头像属性
			// this.memberService.updateMemberAvatar(member.getId(),
			// bAvatar.getId());

			// 更新session中会员头像属性
			// member.setAvatar(bAvatar.getId());
			// SessionUtil.setMemberSession(request, member);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 删除临时文件
			FileUtils.deleteQuietly(file);
			// 删除数据库临时文件
			// this.resService.delAvatartmp(avatarId);
		}

		return imv;
	}

}
